/*
 * SPDX-FileCopyrightText: 2021 Espressif Systems (Shanghai) CO LTD
 *
 * SPDX-License-Identifier: Unlicense OR CC0-1.0
 */
#ifndef GATTS_TABLE
#define GATTS_TABLE

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"

#include "esp_system.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "esp_bt.h"

#include "esp_gap_ble_api.h"
#include "esp_gatts_api.h"
#include "esp_bt_main.h"
#include "esp_gatt_common_api.h"

#include "esp_vfs.h"
/* wl_handle_t */
#include "esp_vfs_fat.h"
#include "cJSON.h"

#include "inirw.h"
#include "led.h"

#include "math.h"

#define GATTS_TABLE_TAG "GATTS_TABLE_DEMO"

#define ble_get_value_max           20

#define PROFILE_NUM                 1
#define PROFILE_APP_IDX             0
#define ESP_APP_ID                  0x55
#define SAMPLE_DEVICE_NAME          "ESP_GATTS_DEMO"
#define SVC_INST_ID                 0

/* The max length of characteristic value. When the GATT client performs a write or prepare write operation,
*  the data length must be less than GATTS_DEMO_CHAR_VAL_LEN_MAX.
*/
#define GATTS_DEMO_CHAR_VAL_LEN_MAX 500
#define PREPARE_BUF_MAX_SIZE        1024
#define CHAR_DECLARATION_SIZE       (sizeof(uint8_t))

#define ADV_CONFIG_FLAG             (1 << 0)
#define SCAN_RSP_CONFIG_FLAG        (1 << 1)

#define EXAMPLE_FATFS_MODE_READ_ONLY false

extern QueueHandle_t QHandle;

/* Attributes State Machine */
enum
{
    IDX_SVC,
    IDX_CHAR_A,
    IDX_CHAR_VAL_A,
    IDX_CHAR_CFG_A,

    IDX_CHAR_B,
    IDX_CHAR_VAL_B,

    IDX_CHAR_C,
    IDX_CHAR_VAL_C,

    HRS_IDX_NB,
};

/**
 * @brief 
 * 
 */
struct esp_device_config{
    /* wifi config*/
    char inissid[32];
    char inipassword[16];

    /* bps */
    int32_t bps485; 
    int32_t bpscan;

    /* tcp-server config */
    char serip[32];
    int32_t port;

    uint32_t seatbeltSensorId;
    uint8_t seatbeltIsUsed;

    /** 
     * （speedSelect）用于设置速度的来源，默认值速度来自CAN总线 通过蓝牙设置
     * True=speedSelect速度来自车载的CAN总线
     * False=speedSelect速度来自io口的开关量信号
     */
    uint8_t speedSelect;
    uint64_t ioSpeedFix;
};

typedef struct {
    uint8_t                 *prepare_buf;
    int                     prepare_len;
} prepare_type_env_t;

/**
 * @brief 
 * 用于保存从ecu232读到的ecu数据的结构体
 */
struct get_serial_ecuinfo{
    char ecu_info[128];
    int len;
    char tcp_flag;
    char ble_flag;
};


#define ECU_DATA_LEN 128
/**
 * @brief 
 * 放入队列的数据的结构体,放入队列的数据的结构体,从队列提取数据下发到232口
 * ecu_data是数据体
 * data_len数据长度
 */
struct ecu_to_serial{
    unsigned char data[ECU_DATA_LEN];
    int len;
};

void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param);

void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param);

void getInitFileData(struct esp_device_config *temp_init);

#endif